package com.yanqu.road.server.push.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eErrorCode;
import com.yanqu.road.entity.util.ResponseUtil;
import com.yanqu.road.server.manger.DataUploadInfoMgr;
import com.yanqu.road.queue.LogAnalysisPushQueue;
import com.yanqu.road.utils.http.HttpHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;


/**
 * @author duli
 * @version 1.0
 * @date 2020/9/9 11:06
 * @Description 日志分析
 */
public class LogAnalysisHolder {
    protected static Logger log = LogManager.getLogger(LogAnalysisHolder.class.getName());
    private JSONObject jsonObject = new JSONObject();
    private static final int pollSize = 200;

    /**
     * 线程池执行消息队列
     */
    public void execute() {
        if (!DataUploadInfoMgr.isAllowUpload()) {
            return;
        }
        String result = "";
        try {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Content-Type", "application/json");
            JSONArray jsonArray = LogAnalysisPushQueue.poll(1000);
            jsonObject.put("appId", DataUploadInfoMgr.getDataUploadInfo().getAppId());
            if (!jsonArray.isEmpty()) {
                log.info("LogAnalysisPushQueue poll size:"+jsonArray.size());
                jsonObject.put("data", jsonArray);
                result = HttpHelper.doPostJsonTimeOut(DataUploadInfoMgr.getDataUploadInfo().getAnalysisBackendUrl(), jsonObject.toJSONString(), "UTF-8", headerMap);
            }

        } catch (Exception e) {
            log.error("命令[批量上报]处理异常...", e);
        } finally {
            if (!result.isEmpty()) {
                wrapperResult(result);
            }
        }
    }

    private void wrapperResult(String result) {
        try {
            ResponseUtil responseUtil = JSON.parseObject(result, ResponseUtil.class);
            if (responseUtil.getState() == eErrorCode.SYSTEM_ERROR.getCode()) {
                log.error("push faild,send message is" + jsonObject);
                log.error("call back message is" + result);
            }else{
//                log.info("push send message is" + jsonObject);
                log.info("call back message is" + result);
            }
        } catch (Exception e) {
            log.error(e.getMessage() + ";send message is:" + jsonObject);
            log.error("call back message is" + result);
        }
    }

}
